package sing.cloud.alibaba.seata.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

/**
 * @author xing
 * @date 2022/9/3 17:54
 */
@Configuration
@EnableConfigurationProperties(MybatisProperties.class)
public class DataSourceProxyConfig {

    /**
     * IDEA 提示：将这个字段值直接注入到 sqlSessionFactoryBean 中，是使用它的唯一方法 <br>
     * 这里可以将写到 下边 sqlSessionFactoryBean 的 Bean 方法作为参数去自动注入，不会有提示 <br>
     * 此写法参考 {@link org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration MybatisAutoConfiguration} 类，它是构造函数自动注入，我这里直接注入
     */
    @Autowired
    private MybatisProperties properties;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    @Bean("dataSource")
    public DataSource dataSource(DataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        //factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        factory.setMapperLocations(this.properties.resolveMapperLocations());
        factory.setTransactionFactory(new SpringManagedTransactionFactory());
        //
        factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        // mybatis 中自动注入类用的 applyConfiguration(SqlSessionFactoryBean factory) 方法，会再做处理，会更复杂一些。
        factory.setConfiguration(this.properties.getConfiguration());
        return factory.getObject();
    }

}
